#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id$
import sys
sys.path.append('..')
import os.path
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import SIGNAL, SLOT, QObject
import re
import time
from locale import getpreferredencoding as penc
import progress_ui, sidialogs


#self.sub = QtCore.QProcess()
#self.sub.setProcessChannelMode(QtCore.QProcess.MergedChannels)
#QtCore.QObject.connect(self.sub, SIGNAL('finished(int)'), self.onsub_finished)
#QtCore.QObject.connect(self.sub, SIGNAL('readyReadStandardOutput()'), self.onsub_data)

dlg = None
prc = None
#app = None

cmd = re.compile(u'PROGRESS\s(?P<level>\d+):\s\[(?P<percent>\d*)\]\s*(?P<msg>.*)', re.I | re.U)

do_quit = False

def on_cancel():
	global do_quit
	if prc:
		if prc.state() != prc.NotRunning: prc.kill()
		do_quit = True
		QtGui.qApp.exit()

def on_text():
	if prc:
		#print "*",
		while prc.canReadLine() and not do_quit:
			QtGui.qApp.processEvents()
			s = unicode(str(prc.readLine()).strip(), penc())
			#print ":",unicode(s, penc())

			if s.startswith(u'PROGRESS'):
				r = cmd.search(s)
				if r:
					a,b,c = r.groups()[0], r.groups()[1],r.groups()[2]
					try:
						b = int(b)
					except:
						b = None
					if a == u'1':
						dlg.progress1(c, b)
						if not b and c and c.strip(): dlg.progress3(c.strip())
					elif a == u'2': dlg.progress2(c, b)
					elif a == u'3': dlg.progress3(c)
				QtGui.qApp.processEvents()
					#time.sleep(0.2)
			else:
				dlg.progress3(s)
		if prc.state() == prc.NotRunning:
			#QtGui.qApp.exit()
			#dlg.ui.bCancel.setText(u"Close")
			dlg.cancel2exit()
			QtGui.qApp.processEvents()

def on_finished(aint):
	print "subprocess finished. code: %s" % (aint,)
	bb = prc.bytesAvailable() if prc else 0
	if dlg and bb==0:
		dlg.cancel2exit()
	#	dlg.close()
	#	QtGui.qApp.exit()


def on_start():
	print "started... in '%s'" % (prc.workingDirectory())

def on_error(err):
	print "error. %s" % (err,)

if __name__=="__main__":
	#global d
	#global dlg, prc
	import doctest

	doctest.testmod()

	app = QtGui.QApplication(sys.argv)

	dlg = sidialogs.Progress() #AProgressBar()
	prc = QtCore.QProcess()

	prc.setProcessChannelMode(QtCore.QProcess.MergedChannels)
	prc.closeWriteChannel()
	prc.setWorkingDirectory( os.path.normpath( os.path.join(os.path.dirname(__file__), '..')))
	QObject.connect(prc, SIGNAL('finished(int)'), on_finished)
	QObject.connect(prc, SIGNAL('readyReadStandardOutput()'), on_text)
	QObject.connect(prc, SIGNAL('started()'), on_start)
	QObject.connect(prc, SIGNAL('error(QProcess::ProcessError)'), on_error)


	#d = AProgressBar()
	#t = QtCore.QTimer(app)
	#QObject.connect(dlg.ui.bCancel, SIGNAL('clicked()'), on_cancel)
	#QObject.connect(dlg.ui.bCancel, SIGNAL('clicked()'), QtGui.qApp, SLOT('quit()'))
	QObject.connect(dlg, SIGNAL('rejected()'), on_cancel)
	#QObject.connect(t, SIGNAL('timeout()'), onTimer)

	dlg.show()
	dlg.center()

	#if sys.platform != 'win32':
	#	prc.start('cat',['../test.log'], QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text)
	#else:
	#	prc.start('cmd', ['/C', 'type ..\\test.log'], QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text)

	print "Workdir:", prc.workingDirectory()
	args = ['samizdat.py', '--progress']
	if len(sys.argv)>1: args.extend(sys.argv[1:])

	prc.start('python', args, QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text)

	app.exec_()
